package com.xuetang9.fujian.jedis;

import redis.clients.jedis.Jedis;

import java.io.*;

/**
 * @describe:
 * @author:fujian
 * @date:2021/6/13
 * @Version: V1.0
 * @Package: com.xuetang9.fujian.jedis
 */
@SuppressWarnings("all")
public class DBConnection {
    private String ip = "47.98.129.48";
    private int port = 6379;
    private Jedis jedis;
    public boolean connect(){
        jedis = new Jedis(ip,port);
        jedis.connect();
        return true;
    }

    public void close(){
        if (jedis != null){
            jedis.close();
        }
    }

    public void save(String key, Serializable data){
        byte[] keyBytes = objectToByte(key);
        byte[] dataByte = objectToByte(data);
        jedis.set(keyBytes,dataByte);
    }

    public void delete(String key){
        byte[] keyByte = objectToByte(key);
        jedis.del(keyByte);
    }

    public Object get(String key){
        byte[] keyBytes = objectToByte(key);
        byte[] dataBytes = jedis.get(keyBytes);
        Object data = bytes2Object(dataBytes);
        return data;
    }

    public byte[] objectToByte(Serializable data){
        byte[] bytes = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream =  new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(data);
            bytes = byteArrayOutputStream.toByteArray();
            objectOutputStream.close();
            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public Object bytes2Object(byte[] bytes){
        Object data = null;
        if (bytes == null || bytes.length == 0){
            return data;
        }

        try{
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            data = objectInputStream.readObject();
            objectInputStream.close();
            byteArrayInputStream.close();
        }catch (IOException | ClassNotFoundException e){
            e.printStackTrace();
        }
        return data;
    }


    public static void main(String[] args) {
        DBConnection dbConnection = new DBConnection();
        boolean connect = dbConnection.connect();
        if (connect){
            dbConnection.save("name","chawuciren");
            System.out.println(dbConnection.get("name"));
            dbConnection.close();
        }
    }


}
